package com.bailan.foreat.service.impl;

import com.bailan.foreat.entity.Product;
import com.bailan.foreat.entity.ProductType;
import com.bailan.foreat.entity.Protype;
import com.bailan.foreat.entity.Store;
import com.bailan.foreat.es.ESDataWriter;
import com.bailan.foreat.es.ESProductRepository;
import com.bailan.foreat.mapper.ProductMapper;
import com.bailan.foreat.mapper.ProductTypeMapper;
import com.bailan.foreat.mapper.ProtypeMapper;
import com.bailan.foreat.mapper.StoreMapper;
import com.bailan.foreat.service.ProductService;
import com.bailan.foreat.utils.TextWrite;
import com.bailan.foreat.vo.EsProduct;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Optional;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ste
 * @since 2023-02-21 07:50:43
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    ProductMapper productMapper;
    @Autowired
    StoreMapper storeMapper;

    @Autowired
    ProtypeMapper protypeMapper;
    @Autowired
    ProductTypeMapper productTypeMapper;

    @Autowired
    ESProductRepository esProductRepository;

    @Autowired
    @Qualifier("esProduct")
    ESDataWriter esDataWriter;

    @Override       //增加餐品
    public int addProduct(Integer storeId, Product product,@RequestParam("chooseTypes[]") Integer[] chooseTypes) {

        Product newProduct = new Product();
        newProduct.setProductName(product.getProductName());
        newProduct.setProductImg("http://localhost:10002/imgs/"+product.getProductImg());
        newProduct.setProductPrice(product.getProductPrice());
        newProduct.setType(product.getType());
        newProduct.setStockCount(product.getStockCount());
        newProduct.setBuyCount(product.getBuyCount());
        newProduct.setStoreId(storeId);
        newProduct.setStatus(product.getStatus());
        int i1 = productMapper.insert(newProduct);

        Integer productId = newProduct.getId();

        int i=0;
        ArrayList<String> typeName = new ArrayList<>();
        ArrayList<Integer> typeIds = new ArrayList<>();
        for (Integer chooseType : chooseTypes) {
            Protype newOne = new Protype();
            newOne.setProductId(productId);
            newOne.setTypeId(chooseType);
            protypeMapper.insert(newOne);
            i++;
            newOne=null;

            ProductType productType = productTypeMapper.selectById(chooseType);
            typeIds.add(chooseType);
            typeName.add(productType.getTypeName());
        }

        TextWrite.textWrite(newProduct.getProductName());
        esProductRepository.deleteAll();
        esDataWriter.dataWrite();

        
        //修改es库存和销量
        Store store = storeMapper.selectById(storeId);
        EsProduct esProduct = new EsProduct(
                newProduct.getId(),
                newProduct.getProductName(),
                newProduct.getProductPrice(),
                newProduct.getProductImg(),
                newProduct.getStockCount(),
                newProduct.getBuyCount(),
                0,
                newProduct.getStoreId(),
                store.getStoreName(),
                newProduct.getStatus(),
                typeName,
                typeIds
        );
        esProductRepository.save(esProduct);
        return i+i1;
    }

    @Override
    public int deleteProduct(Integer productId) {
        int i = productMapper.deleteProType(productId);
        int i1 = productMapper.deleteById(productId);

        //修改es库存和销量
        //下架则从es删除
        esProductRepository.deleteById(Long.valueOf(productId));


        return i + i1;
    }

    @Override
    public int updateProduct(Product product) {

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", product.getId());
        Product p = productMapper.selectOne(queryWrapper);
        p.setId(product.getId());
        p.setProductName(product.getProductName());
        p.setProductImg(product.getProductImg());
        p.setProductPrice(product.getProductPrice());
        p.setType(product.getType());
        p.setStockCount(product.getStockCount());
        p.setBuyCount(product.getBuyCount());
        p.setStoreId(product.getStoreId());
        p.setStatus(product.getStatus());

        //修改es库存和销量
        //下架则从es删除
        if (p.getStatus() == 1){
            esProductRepository.deleteById(Long.valueOf(p.getId()));
        }else{
            Optional<EsProduct> byId = esProductRepository.findById(Long.valueOf(p.getId()));
            EsProduct oldEs = byId.get();
            oldEs.setStockCount(p.getStockCount());
            oldEs.setProductPrice(p.getProductPrice());
            oldEs.setStatus(p.getStatus());

            esProductRepository.deleteById(Long.valueOf(p.getId()));
            esProductRepository.save(oldEs);
        }




        return productMapper.updateById(p);
    }

    @Override
    public Page<Product> selectProduct(Integer storeId, Integer currentPage, Integer pageSize) {

        Page<Product> page = new Page<>(currentPage, pageSize);

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);

        Page<Product> proPageResult = productMapper.selectPage(page, queryWrapper);

        return proPageResult;
    }

    @Override
    public Page<EsProduct> searchByES(Integer currentPage, Integer pageSize, String keyName) {
        //判断es是否有数据,如果没有数据就写入
        if (!esProductRepository.findAll().iterator().hasNext())
            esDataWriter.dataWrite();
        //es查询
        //构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        WildcardQueryBuilder query1 = null;

        //query
        if (!"".equals(keyName) && keyName != null) {
            query1 = QueryBuilders.wildcardQuery("productName", keyName);
        }

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (query1 != null)
            boolQueryBuilder.must(query1);


        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        //分页条件
        //注意: es中的分页是从第0页开始的

        nativeSearchQueryBuilder.withPageable(PageRequest.of(currentPage - 1, pageSize));

        //排序
//        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("buyCount").order(SortOrder.DESC));

        org.springframework.data.domain.Page<EsProduct> esProductPage = esProductRepository.search(nativeSearchQueryBuilder.build());

        //将 Es的page 转换 mybatisPlus的 page
        Page<EsProduct> productPage = new Page<>(currentPage, pageSize);
        productPage.setPages(esProductPage.getTotalPages());
        productPage.setTotal(esProductPage.getTotalElements());
        productPage.setRecords(esProductPage.getContent());

        return productPage;
    }

    @Override
    public Product selectById(Integer id) {
        Product product = productMapper.selectById(id);
        return product;
    }

    //@Override
    //public List<Product> selectProduct(Integer storeId) {
    //    QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
    //    queryWrapper.eq("store_id", storeId);
    //    List<Product> products = productMapper.selectList(queryWrapper);
    //    return products;
    //}
}
